import re
import urllib2

from HTMLParser import HTMLParser


class ComicBook:
    def __init__(self, url):
        self.url = url
        self.title = 'Untitled'
        self.pages = 0
        self.images = 0
        self.pages_url = []
        self.images_url = []

        self.parse_url()
        self.get_pages_url()
        self.get_images_url()

    def parse_url(self):
        try:
            req = urllib2.Request(self.url, headers={'User-Agent': "Magic Browser"})
            con = urllib2.urlopen(req)
            s = con.read().decode(con.headers.getparam('charset'))
            parser = ComicBookParser(self)
            parser.feed(s)
            print 'Parsed %s and got comic book << %s (%d images) >>' % \
                (self.url, self.title, self.images)
        except urllib2.HTTPError, e:
            print e

    def get_pages_url(self):
        self.pages_url = [self.url] * self.pages
        for i in range(1, self.pages):
            self.pages_url[i] += '?p=%d' % i

    def get_images_url(self):
        for url in self.pages_url:
            req = urllib2.Request(url, headers={'User-Agent': "Magic Browser"})
            con = urllib2.urlopen(req)
            s = con.read().decode(con.headers.getparam('charset'))
            parser = ComicBookPageParser()
            parser.feed(s)
            self.images_url.extend(parser.images_url)


class ComicBookParser(HTMLParser):
    def __init__(self, comic_book):
        HTMLParser.__init__(self)
        self.comic_book = comic_book
        self.capture_title = False
        self.capture_pages = False
        self.capture_images = False

    def handle_starttag(self, tag, attrs):
        if tag == 'h1':
            for attr in attrs:
                if attr[0] == 'id':
                    if attr[1] == 'gn' or attr[1] == 'gj':
                        self.capture_title = True
        elif tag == 'p':
            for attr in attrs:
                if attr[0] == 'class' and attr[1] == 'gpc':
                    self.capture_images = True

    def handle_endtag(self, tag):
        self.capture_title = False
        self.capture_pages = False
        self.capture_images = False

    def handle_data(self, data):
        if self.capture_title and len(data) > 0:
            self.comic_book.title = data
        elif self.capture_images:
            self.parse_images_and_pages(data)

    def parse_images_and_pages(self, s):
        m = re.match('Showing \d+ - \d+ of (\d+) images', s)
        if m:
            self.comic_book.images = int(m.groups()[0])
            self.comic_book.pages = (self.comic_book.images + 39) / 40


class ComicBookPageParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.images_url = []
        self.last_href_url = ''

    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            for attr in attrs:
                if attr[0] == 'href':
                    self.last_href_url = attr[1]
        elif tag == 'img':
            for attr in attrs:
                if attr[0] == 'title' and attr[1][:4] == 'Page':
                    self.images_url.append(self.last_href_url)
